<template>
  <div>
    <div id="parent" class="list">
      <el-button class="list-title" type="primary" v-if="mqMesgList.length === 0"
                 @click="handleClick">
        换药 | 求助 ({{ mqMesgList.length }})
      </el-button>
      <el-button class="list-title" type="warning" v-else @click="handleClick">
        换药 | 求助 ({{ mqMesgList.length }})
      </el-button>
      <el-scrollbar v-if="listVisible">
        <el-card class="box-card" v-for="mesg in mqMesgList" style="border-width: 1px">
          <div style="font-size: 0.7em; margin: -7px">
            <el-tag v-if="mesg.type==='change'" size="mini" type="warning">换药</el-tag>
            <el-tag v-else size="mini" type="danger">求助</el-tag>
<!--            如果mesg.body.role是room则不加床，否加床-->
            <el-tag v-if="mesg.body.role==='room'" size="mini">{{ mesg.body.id }}</el-tag>
            <el-tag v-else size="mini">{{ mesg.body.id }}床</el-tag>
<!--            {{ mesg.body.id }}床-->
            <el-button style="float: right; margin-top: -3px" type="success" size="mini"
                       @click="process_mqMesgList(mesg)" plain>处理
            </el-button>
          </div>
        </el-card>
      </el-scrollbar>
    </div>
  </div>
</template>

<script>
import Stomp from 'stompjs';//注意引用的方式，不要加{}
import {useStore} from "vuex";
import {onMounted, onUnmounted, computed, watch, ref} from 'vue';
import {
  MQ_PROTOCOL, MQ_IP, MQ_PORT,
  MQ_ADDRESS, MQ_ACCOUNT,
  MQ_PASSWORD, MQ_SUBSCRIPT, MQ_VHOST
} from '../utils/sysconstant';
import {findByQno, signal} from "../api/call";

export default {
  name: "MessageNotice",


  setup() {
    //mq相关
    let store = useStore()
    let address = null;//连接地址
    let client = null;
    let subscribes = {};
    //列表是否显示
    const listVisible = ref(false);
    let mqMesgList = computed(() => store.state.mqMesgList);
    let status = false

    onMounted(() => {
      address = MQ_PROTOCOL + '://' + MQ_IP + ':' + MQ_PORT + '/' + MQ_ADDRESS;
      connect();
      setInterval(() => {
        if (status) {
          console.log("连接正常")
        } else {
          console.log("连接断开")
          location.reload()
        }
      }, 10000)
      // document.onkeydown = function (e) {
      //   debugger
      //   const ctrlKey = e.ctrlKey;
      //   const charCode = e.key;
      //   if (ctrlKey && charCode === "q") {
      //     //调用MessageNotice组件的方法process_mqMesgList
      //
      //     process_mqMesgList(mqMesgList.value[0])
      //   }
      // }
      //模拟组合键触发函数

        let self = this;
        let code = 0;
        let code2 = 0;
        document.onkeydown = function(e){
          let evn = e || event ;
          let key = evn.keyCode || evn.which || evn.charCode ;
          if(key === 17){
            code = 1 ;
          }
          if(key === 13){
            code2 = 1;
          }
          if(code === 1 && code2 === 1){
            process_mqMesgList(mqMesgList.value[0])
            //do something
            code = 0;
            code2 = 0;
          }
        }
        document.onkeyup = function(e){
          if (e.keyCode === 17) {
            code = 0;
          }
          if (e.keyCode === 13) {
            code2 = 0;
          }
        }


    })

    function connect() {
      client = Stomp.client(address)	//填写地址，ws://+ip+端口+/ws
      client.connect(MQ_ACCOUNT, MQ_PASSWORD, onConnected, onFailed, MQ_VHOST);	//参数依次为：用户名，密码，连接后，出错
    }

    // watchEffect(() => {
    //
    // })
    function onFailed(errorMsg) {
      disconnect()
      console.log('出现错误，status变为false');
      status = false
      console.error(`stomp 断开连接，正在准备重新连接...`, errorMsg)
      console.log('WebSocket发生错误: ' + errorMsg.code)
      // connect()
    }

    function onConnected(frame) {
      console.log('连接成功，status变为true');
      status = true
      console.log("Connected: " + frame);
      subscribe()
    }

    //订阅
    function subscribe() {
      if (!client) {
        console.info('暂未连接')
        return;
      }
      if (!client.connected) {
        console.info('暂未连接')
        return;
      }
      if (subscribes[MQ_SUBSCRIPT]) {
        console.info('已经订阅了')
        return;
      }
      subscribes[MQ_SUBSCRIPT] = client.subscribe(MQ_SUBSCRIPT, responseCallback);
    }

    //回调
    function responseCallback(frame) {
      let val = JSON.parse(frame.body)
      if (!val.body.ask) {
        store.commit('PROCESS_MQMESGLIST', val)
      } else if (val.body.ask) {
        store.commit('SET_MQMESGLIST', val)
      }
    }

    //从浏览器本地存储中获取数据
    const getData = () => {
      //切记注意ref获取数据要加.value(耗费太长时间)

      if (sessionStorage.getItem('vue-chat-mqMesgList') == null) {
        sessionStorage.setItem('vue-chat-mqMesgList', JSON.stringify([]))
      } else {
        store.state.mqMesgList = JSON.parse(sessionStorage.getItem('vue-chat-mqMesgList'))
        console.log('从session获取数据',mqMesgList)
      }
    }
    getData()
    // console.log("mqMesgList------", mqMesgList.value);

    //取消订阅
    function unsubscribe() {
      if (subscribes[MQ_SUBSCRIPT]) {
        subscribes[MQ_SUBSCRIPT].unsubscribe();
        delete subscribes[MQ_SUBSCRIPT];
      }
    }

    //页面关闭断开连接
    onUnmounted(() => {
      disconnect();
    })

    //断开连接
    function disconnect() {
      if (client && client.connected) {
        client.disconnect(() => {
          console.log('断开连接，status变为false');
          status = false
          subscribes = {};
          console.info('断开连接!')
        })
      }
    }


    //监听按钮点击
    function handleClick() {
      listVisible.value = !listVisible.value
    }

    function process_mqMesgList(val) {
      // debugger
      store.commit('PROCESS_MQMESGLIST', val)
      const qno = val.body.id;
      let zhCnRole="";
      let tmpRole=val.body.role;
      if(tmpRole=="bed"){
        zhCnRole="床";
      }
      if(tmpRole=="room"){
        zhCnRole="";
      }
      //判断type是change、help、call
      let zhCnType="已处理";
      let tmpId2=qno.replace("-","");
      let text=tmpId2+zhCnRole+zhCnType;
      const msg = new SpeechSynthesisUtterance();
      msg.text = text;
      // window.speechSynthesis.speak(msg);
      const p = findByQno(qno);
      if (p === null) return
      signal(p.bedId, false, val.type);
    }

    return {
      listVisible,
      mqMesgList,
      handleClick,
      process_mqMesgList,
    }
  }

}
</script>

<style scoped>
.list {
  position: absolute;
  right: 200px;
  top: 16px;
  cursor: pointer;
  z-index: 888;
}

.list-title {
  border-radius: 5px;
  box-shadow: 5px 5px 5px 5px rgba(0, 0, 0, 0.5);
  width: 180px;
  height: 20px;
}

</style>
